<?php

/**
 * Yii Controller BookController
 * This is test
 * @author nguyenmanhluu
 * @since Sep 17, 2013 - 5:54:16 PM
 */
class BookingController extends FrontController {

    public $layout = '//layouts/booking';
    public $result;
    public $service;
    public $cus_id; // id cua customer trong bang tbl_customer
    public $order_id;
    public $start_time; // start time book hotdeal
    public $cus_email = FALSE;
    public $cus_model; //model of customer at tbl_customer

    public function accessRules() {
        return CMap::mergeArray(parent::accessRules(), array('allow', // allow authenticated user to perform 'create' and 'update' actions
                    'actions' => array('asyncUpload', 'asyncDelete'),
                    'users' => array('@'),
        ));
    }

    public function actionCreateRequest() {

        $mid = $_POST['mid'];

        //check user exist
        $user = Users::check_exist_by_email($_POST['email'], Users::TYPE_CUSTOMER);

        if ($user) {

            $this->update_user($user);
            //kiem tra customer co thuoc biz hay khong 
            $check_cus_biz = Customer::checkCustomerBelongToBiz($user->id, $mid);

            if ($check_cus_biz) {
                $this->createRequestBooking($check_cus_biz, $mid);
            } else {

                $new_cus = $this->createCustomerBiz($user->id, $mid);

                if ($new_cus) {
                    $this->createRequestBooking($new_cus, $mid);
                } else {
                    echo json_encode(array(
                        'status' => 'err',
                    ));
                    Yii::app()->end();
                }
            }
        } else {
            echo json_encode(array(
                'status' => 'err',
            ));
            Yii::app()->end();
        }
    }

    /**
     * 
     * @param CActiveRecord $user
     */
    public function update_user($user) {

        $user->firstname = $_POST['fname'];
        $user->lastname = $_POST['lname'];
        $user->mobile_phone = $_POST['phone'];
        $user->address = $_POST['address'];
        $user->postal_code = $_POST['postal_code'];

        $birthday = ($_POST['birthday'] != '') ? str_replace('/', '-', $_POST['birthday']) : NULL;
        $user->birthday = ($birthday) ? strtotime($birthday) : '';

        if ($user->update()) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * 
     * @param int $id_customer
     */
    public function createRequestBooking($customer, $mid) {

        $requestbooking = new RequestBooking();

        $requestbooking->request_time_1 = $_POST['date_1'] . ' ' . $_POST['time_1'];
        $requestbooking->request_time_2 = $_POST['date_2'] . ' ' . $_POST['time_2'];
        $requestbooking->request_time_3 = (trim($_POST['date_3'] != '')) ? $_POST['date_3'] . ' ' . $_POST['time_3'] : NULL;

        $requestbooking->service_name = $_POST['sname'];
        $requestbooking->note = $_POST['note'];
        $requestbooking->merchant_id = $mid;
        $requestbooking->status = RequestBooking::STATUS_PENDING;
        $requestbooking->customer_id = $customer->id;
        $requestbooking->notify = RequestBooking::HAVE_NOTICE;
        $requestbooking->date_time_request = time();

        if ($requestbooking->validate() AND $requestbooking->save()) {

            try {
                MyEmail::send_booking_request_to_customer($requestbooking);
                MyEmail::send_booking_new_request_to_conceirge($requestbooking);
                Yii::app()->session->remove('request_book');
            } catch (Exception $ex) {
                
            }

            echo json_encode(array(
                'status' => 'ok',
                'cus_email' => $_POST['email'],
                'cus_name' => $_POST['fname'] . ' ' . $_POST['lname'],
                'cus_key' => $customer->ckey
            ));


            Yii::app()->end();
        } else {
            echo json_encode(array(
                'status' => 'err',
            ));
            Yii::app()->end();
        }
    }

    public function actionIndex1() {
        
        if (!isset($_GET['service'])) {
            throw new CHttpException(404, 'Not found Service line:23');
        }
        unset(Yii::app()->session['offset_review']);
        unset(Yii::app()->session['email_has_1stdiscount']);
        //tim hotdeal theo service
        $hotdeal = Hotdeal::model()->find("sid=:sid", array(":sid" => $_GET['service']));
        
        if (Yii::app()->user->isGuest) {
            $customer = new Users();
            if (isset($_POST['ajax']) && $_POST['ajax'] === 'book-form') {
                echo CActiveForm::validate($customer);
                Yii::app()->end();
            }
        } else {
            
            //optimize query
//            $customer = Users::model()->findByPk(Yii::app()->user->id);
            $customer=Yii::app()->user->getCurrentUser();  
        }
        $status = 1;
        $model = Service::model()->findByPk($_GET['service']);
        //Check customer of merchant is block 
        $thefirst=FALSE;
        if (Customer::is_1st_with_current_user($model->user->ukey))
            $thefirst = Thefirst::model()->find("sid=:sid", array(":sid" => $_GET['service']));
        
        $check_cus_biz = Customer::checkCustomerBelongToBiz($customer->id, $model->author_id);
        if ($check_cus_biz) {
            if ($check_cus_biz->status == Customer::STATUS_BLOCK) {
                $status = 0;
                Yii::app()->user->setFlash('error', Yii::t('frontend','Your account is blocked with this merchant'));
            }
        }
        if ($model->user->status == Users::STATUS_BLOCK) {
            //$status = 0;
            //Yii::app()->user->setFlash('error', 'Merchant not available');
            //Yii::app()->request->redirect(Yii::app()->createUrl('frontend/booking/RequestService'));
        } elseif ($model->user->status == Users::STATUS_TRIAL) {
            Yii::app()->request->redirect(Yii::app()->createUrl('frontend/booking/trialBooking', array('service' => $model->sid)));
        }

        if (isset($_GET['t']) && trim($_GET['t']) != "")
            $page = trim($_GET['t']);
        else
            $page = "";
        
        
        if ($status == 0) {

            $this->render('error_page');
        } else {
            if ($page == 'embed') {
                $this->layout = '//layouts/bookingembed';
                $this->render('indexembed', array(
                    'service' => $model,
                    'customer' => $customer,
                    'hotdeal' => $hotdeal,
                    'thefirst' => $thefirst
                ));
            } else {
                $this->render('index', array(
                    'service' => $model,
                    'customer' => $customer,
                    'hotdeal' => $hotdeal,
                    'thefirst' => $thefirst
                ));
            }
        }
    }


    /**
     * @param string $biz
     * @param string $sUrl
     */
    public function actionIndex($biz='',$sUrl='') {

        if (!isset($_GET['service'])) {
            $model = Service::model()->findByAttributes(array(
                'alias'=>$sUrl,
                'author_id'=>$this->biz->id,
            ));


        }
        else {
            $model = Service::model()->findByPk(intval($_GET['service']));
        }

        if(!$model){
            Yii::app()->request->redirect('frontend/site/error');
            //die;
        }
        //FindAuthorID
        //$model = Service::model()->findByPk($_GET['service']);
//        echo $sUrl;
//        echo $this->biz->id;


        unset(Yii::app()->session['offset_review']);
        //tim hotdeal theo service
        //$hotdeal = Hotdeal::model()->find("sid=:sid", array(":sid" => $_GET['service']));
        $hotdeal = Hotdeal::model()->find("sid=:sid", array(":sid" => $model->sid));

        if (Yii::app()->user->isGuest) {
            $customer = new Users();
            if (isset($_POST['ajax']) && $_POST['ajax'] === 'book-form') {
                echo CActiveForm::validate($customer);
                Yii::app()->end();
            }
        } else {

            //optimize query
//            $customer = Users::model()->findByPk(Yii::app()->user->id);
            $customer=Yii::app()->user->getCurrentUser();
        }
        $status = 1;
        //$model = Service::model()->findByPk($_GET['service']);

        //Check customer of merchant is block
        $thefirst=FALSE;
        if (Customer::is_1st_with_current_user($model->user->ukey)){
            //$thefirst = Thefirst::model()->find("sid=:sid", array(":sid" => $_GET['service']));
            $thefirst = Thefirst::model()->find("sid=:sid", array(":sid" => $model->sid));
        }


        $check_cus_biz = Customer::checkCustomerBelongToBiz($customer->id, $model->author_id);
        if ($check_cus_biz) {
            if ($check_cus_biz->status == Customer::STATUS_BLOCK) {
                $status = 0;
                Yii::app()->user->setFlash('error', Yii::t('frontend','Your account is blocked with this merchant'));
            }
        }
        if ($model->user->status == Users::STATUS_BLOCK) {
            //$status = 0;
            //Yii::app()->user->setFlash('error', 'Merchant not available');
            //Yii::app()->request->redirect(Yii::app()->createUrl('frontend/booking/RequestService'));
        } elseif ($model->user->status == Users::STATUS_TRIAL) {
            Yii::app()->request->redirect(Yii::app()->createUrl('frontend/booking/trialBooking', array('service' => $model->sid)));
        }

        if (isset($_GET['t']) && trim($_GET['t']) != "")
            $page = trim($_GET['t']);
        else
            $page = "";


        if ($status == 0) {

            $this->render('error_page');
        } else {
            if ($page == 'embed') {
                $this->layout = '//layouts/bookingembed';
                $this->render('indexembed', array(
                    'service' => $model,
                    'customer' => $customer,
                    'hotdeal' => $hotdeal,
                    'thefirst' => $thefirst
                ));
            } else {
                $this->render('index', array(
                    'service' => $model,
                    'customer' => $customer,
                    'hotdeal' => $hotdeal,
                    'thefirst' => $thefirst
                ));
            }
        }
    }

    public function actionLoadHotdeal() {
        $hot_deal = array();
        if (isset($_POST['get_hot_deal']) && $_POST['get_hot_deal'] == 'yes') {
            $hot_deal = Service::model()->getHotdeal();
        }
        echo json_encode($hot_deal);
        Yii::app()->end();
    }

    public function actionLoadOtherService() {
        $other_service = array();
        if (isset($_POST['get_other_service']) && $_POST['get_other_service'] == 'yes') {
            $other_service = Service::model()->getOtherService();
        }
        echo json_encode($other_service);
        Yii::app()->end();
    }

    public function actionLoadSimiService() {
        $simi_service = array();
        if (isset($_POST['get_simi_service']) && $_POST['get_simi_service'] == 'yes') {
            $simi_service = Service::model()->getSimiService();
        }
        echo json_encode($simi_service);
        Yii::app()->end();
    }

    public function actionKeeper() {
        if (Yii::app()->request->isAjaxRequest) {
            if (isset($_POST['staff'])) {
                Yii::app()->session['booking_staff'] = $_POST['staff'];
            }
            if (isset($_POST['booking_date'])) {
                Yii::app()->session['booking_date'] = $_POST['booking_date'];
            }
            if (isset($_POST['booking_hour'])) {
                Yii::app()->session['booking_hour'] = $_POST['booking_hour'];
            }
            if (isset($_POST['booking_step2_open'])) {
                Yii::app()->session['booking_step2_open'] = $_POST['booking_step2_open'];
            }
            if (isset($_POST['book_open'])) {
                Yii::app()->session['book_open'] = $_POST['book_open'];
            }
            if (isset($_POST['sname'])) {
                Yii::app()->session['sname'] = $_POST['sname'];
            }
        }
    }

    public function actionRequestKeeper() {
        if (Yii::app()->request->isAjaxRequest) {
            if (!isset(Yii::app()->session['request_book']))
                Yii::app()->session['request_book'] = array();

            $arr = array(
                'service_name' => $_POST['service_name'],
                'date_1' => $_POST['date_1'],
                'date_2' => $_POST['date_2'],
                'date_3' => $_POST['date_3'],
                'time_1' => $_POST['time_1'],
                'time_2' => $_POST['time_2'],
                'time_3' => $_POST['time_3'],
                'book_open' => $_POST['book_open']
            );

            Yii::app()->session['request_book'] = $arr;
        }
        echo json_encode(array('status' => 'ok'));
    }

    public function actionClass() {
        $customer_added = FALSE;
        if (!isset($_GET['classid'])) {
            throw new CHttpException(404, 'Not found class line: 147');
        }

        if (Yii::app()->user->isGuest) {
            $customer = new Users();
            if (isset($_POST['ajax']) && $_POST['ajax'] === 'book-form') {
                echo CActiveForm::validate($customer);
                Yii::app()->end();
            }
        } else {
            //check customer added to class?
            $customer = Users::model()->findByPk(Yii::app()->user->id);
            $cri = new CDbCriteria();
            $cri->condition = 't.apt_id=:apt';
            $cri->params = array(':apt' => $_GET['classid']);
            $cri->with = array('customer');
            $cri->compare('customer.user_id', Yii::app()->user->id);
            $apt_cus = AptCustomer::model()->find($cri);
            if ($apt_cus) {
                $customer_added = TRUE;
            }
        }

        $status = 1;
        $class = Appoint::model()->findByPk($_GET['classid']);

        if ($class->service->user->status == Users::STATUS_BLOCK) {
            $status = 0;
            Yii::app()->user->setFlash('error', Yii::t('frontend','Merchant not available'));
        }
        //Check customer of merchant is block 
        $check_cus_biz = Customer::checkCustomerBelongToBiz($customer->id, $class->service->author_id);
        if ($check_cus_biz) {
            if ($check_cus_biz->status == Customer::STATUS_BLOCK) {
                $status = 0;
                Yii::app()->user->setFlash('error', Yii::t('frontend','Your account is blocked with this merchant'));
            }
        }
        if ($status == 0) {
            $this->render('error_page');
        } else {
            if (isset($_GET['t']) && trim($_GET['t']) != "")
                $page = trim($_GET['t']);
            else
                $page = "";
            if ($page == 'embed') {
                $this->layout = "//layouts/mainembed";
                $this->render('class/eindex', array(
                    'class' => $class,
                    'customer' => $customer,
                    'customer_added' => $customer_added
                ));
            } else
                $this->render('class/index', array(
                    'class' => $class,
                    'customer' => $customer,
                    'customer_added' => $customer_added
                ));
        }
    }

    public function actionValidateFormRequest() {
        if (Yii::app()->user->isGuest){
            $customer = new CustomerBookForm;
            $customer->email = $_POST['email'];
        }
        else
            $customer = user()->currentUser;
        $customer->firstname = $_POST['fname'];
        $customer->lastname = $_POST['lname'];
        $customer->mobile_phone = $_POST['phone'];
        $customer->occupation = $_POST['occupation'];
        $customer->address = $_POST['address'];
        $customer->postal_code = $_POST['postal_code'];



        if ($customer->validate()) {
            echo json_encode(array(
                'status' => 1
            ));
            Yii::app()->end();
        } else {
            echo json_encode(array(
                'status' => 0,
                'msg' => CHtml::errorSummary($customer)
            ));
            Yii::app()->end();
        }
    }

    public function actionValidateForm() {
        $service = Service::getRecordbySid($_POST['sid']);
        if (Yii::app()->user->isGuest) {
            /**
             * Booking at Customer's Home: Validate customer address
             */
            if ($service->book_online == Service::BOOKING_CUSTOMER_HOME) {
                $customer = new CustomerBookForm('validate_address');
            } else {
                $customer = new CustomerBookForm;
            }
            $customer->firstname = $_POST['fname'];
            $customer->lastname = $_POST['lname'];
            $customer->email = $_POST['email'];
            $customer->mobile_phone = $_POST['phone'];
            $customer->occupation = $_POST['occupation'];
            $customer->address = $_POST['address'];
            $customer->postal_code = $_POST['postal_code'];
        } else {
            $customer = Users::model()->findByPk(Yii::app()->user->getId());
            if ($service->book_online == Service::BOOKING_CUSTOMER_HOME) {
                $customer->setscenario("validate_address");
            }
            $customer->setScenario('edit_' . Users::TYPE_CUSTOMER);
            $customer->firstname = $_POST['fname'];
            $customer->lastname = $_POST['lname'];
//            $customer->email = $_POST['email'];
            $customer->mobile_phone = $_POST['phone'];
            $customer->occupation = $_POST['occupation'];
            $customer->address = $_POST['address'];
            $customer->postal_code = $_POST['postal_code'];
        }

        if ($customer->validate())
        {
            if (Yii::app()->user->isGuest)
            {
                $date = strtotime(str_replace('/', '-', $_POST['selected_date']));
                $thefirst_discount = 0;
                
                if (Customer::email_is_firsttime_with_merchant($customer->email, $service->author_id))
                {
                    Yii::app()->session['email_has_1stdiscount'] = $customer->email;
                    $thefirst_discount = floatval(Thefirst::getDiscountByTime($service->sid, $date, $_POST['selected_time'], FALSE));
                    $thefirst_record = Thefirst::model()->find("sid=:sid", array(":sid" => $service->sid));
                    $thefirstDays = json_decode($thefirst_record->listDayNotThefirst);
                    $thefirst_openday = $thefirst_record->openday;
                    $thefirst_closeday = $thefirst_record->closeday;
                }
                
                echo json_encode(array(
                    'status' => 1,
                    'thefirst_discount' => $thefirst_discount,
                    'thefirstDays' => $thefirstDays,
                    'thefirst_openday' => $thefirst_openday,
                    'thefirst_closeday' => $thefirst_closeday,
                ));
                Yii::app()->end();
            }

            echo json_encode(array(
                'status' => 1
            ));
            Yii::app()->end();
        }
        else
        {
            echo json_encode(array(
                'status' => 0,
                'msg' => CHtml::errorSummary($customer)
            ));
            Yii::app()->end();
        }
    }


    /**
     * redirect to paypal successfuly and call back this function
     */
    public function actionExecute() {

        $success = isset($_GET['success']) ? $_GET['success'] : '';
        $PayerID = isset($_GET['PayerID']) ? $_GET['PayerID'] : '';

        $paypal = new Paypal;
        $paypal->success = $success;
        $paypal->PayerID = $PayerID;
        $paypal->actionExecutePayment();

        $this->result = $paypal->result; // roi cho nay ong luu cac du lieu can thiet vao db sau do chay tiep actionCreateAppt? 
        $this->checkCustomer();

        //return TRUE if create success and FALSE if otherwise
        $this->createAppt();
        $this->createPayment();
    }

    //check customer belong merchant?
    //Dung rieng cho truong hop redirect paypal
    public function checkCustomer() {
        $this->service = $service = Service::getRecordbySid(urldecode($_GET['sid']));

        $this->cus_email = urldecode($_GET['email']);

        if (!$service) {
            die('not found service' . urldecode($_GET['sid']));
        }

        //create Customer
        if (Yii::app()->user->isGuest) {
            //check customer by email
            $cus = Users::check_exist_by_email(urldecode($_GET['email']), Users::TYPE_CUSTOMER);

            //if not found
            if (FALSE == $cus) {

                //kiem tra xem user co thuoc biz khong
                $check_cus_biz = Customer::checkCustomerBelongToBiz($cus->id, $service->biz->id);

                //neu customer la khach hang cua biz
                //lay id cua customer
                if ($check_cus_biz) {

                    $this->cus_model = $check_cus_biz;

                    $this->cus_id = $cus_id = $check_cus_biz->id;
                } else {
                    $this->cus_model = $new_cus = $this->create_cus_biz($cus->id, $service->biz->id);

                    $this->cus_id = $cus_id = $new_cus->id;
                }
            } else { //if email not exited in tbl_user
                //create new user in
                $user = $this->createCus();

                //create new customer in tbl_customer
                $this->cus_model = $new_cus = $this->create_cus_biz($user->id, $service->biz->id);
                $this->cus_id = $cus_id = $new_cus->id;
            }
        }
        //update Customer
        else {
            $customer = Users::model()->findByPk(Yii::app()->user->getId());

            $customer->firstname = isset($_GET['firstname']) ? urldecode($_GET['firstname']) : '';
            $customer->lastname = isset($_GET['lastname']) ? urldecode($_GET['lastname']) : '';
//            $customer->email = isset($_GET['email']) ? urldecode($_GET['email']) : '';
            $customer->mobile_phone = isset($_GET['phone']) ? urldecode($_GET['phone']) : '';
            $customer->occupation = isset($_GET['occupation']) ? urldecode($_GET['occupation']) : '';

            $birthday = ($_GET['birthday'] != '') ? str_replace('/', '-', urldecode($_GET['birthday'])) : NULL;
            $customer->birthday = strtotime($birthday);
            $customer->address = isset($_GET['address']) ? urldecode($_GET['address']) : '';
            $customer->postal_code = isset($_GET['postal_code']) ? urldecode($_GET['postal_code']) : '';
            $customer->save();

            //kiem tra customer hien tai  co thuoc biz khong?
            $check_cus_biz = Customer::checkCustomerBelongToBiz($customer->id, $service->biz->id);

            if (TRUE == $check_cus_biz) {
                $this->cus_model = $check_cus_biz;
                $cus_id = $check_cus_biz->id;
            } else {
                $this->cus_model = $new_cus = $this->create_cus_biz($customer->id, $service->biz->id);

                $this->cus_id = $cus_id = $new_cus->id;
            }
        }
        $this->cus_id = $cus_id;
        return $cus_id;
    }

    public function actionSuccess() {

        $this->layout = '//layouts/success';
        $this->render('success');
    }

    /**
     * dung rieng cho truong hop redirect link paypal
     * @return mixed <b>FALSE</b> if create falie and <b> a Active record </b> if otherwise
     */
    public function create_cus_biz($id_user, $biz_id) {

        $new_cus = new Customer();

        $new_cus->firstname = isset($_GET['firstname']) ? urldecode($_GET['firstname']) : '';
        $new_cus->lastname = isset($_GET['lastname']) ? urldecode($_GET['lastname']) : '';
        $new_cus->mobile_phone = isset($_GET['phone']) ? urldecode($_GET['phone']) : '';
        $new_cus->address = isset($_GET['address']) ? urldecode($_GET['address']) : '';
        $new_cus->postal_code = isset($_GET['postal_code']) ? urldecode($_GET['postal_code']) : '';

        $new_cus->status = Customer::STATUS_ACTIVE;
        $new_cus->country = Country::DEFAULT_COUNTRY;

        $birthday = ($_GET['birthday'] != '') ? str_replace('/', '-', urldecode($_GET['birthday'])) : NULL;
        $new_cus->birthday = ($birthday) ? strtotime($birthday) : '';

        $new_cus->biz_id = $biz_id;
        $new_cus->user_id = $id_user;

        if ($new_cus->save()) {
            $new_cus->updateCkey();
            return $new_cus;
        } else {
            return FALSE;
        }
    }

    /*
     * Dùng riêng cho trường hợp redirect từ paypal về
     */

    public function createCus() {

        $customer = new CustomerBookForm();
        $customer->firstname = isset($_GET['firstname']) ? urldecode($_GET['firstname']) : '';
        $customer->lastname = isset($_GET['lastname']) ? urldecode($_GET['lastname']) : '';
        $customer->email = isset($_GET['email']) ? urldecode($_GET['email']) : '';
        $customer->mobile_phone = isset($_GET['phone']) ? urldecode($_GET['phone']) : '';
        $customer->occupation = isset($_GET['occupation']) ? urldecode($_GET['occupation']) : '';
        $birthday = ($_GET['birthday'] != '') ? str_replace('/', '-', urldecode($_GET['birthday'])) : NULL;
        $customer->birthday = strtotime($birthday);
        $customer->address = isset($_GET['address']) ? urldecode($_GET['address']) : '';
        $customer->postal_code = isset($_GET['postal_code']) ? urldecode($_GET['postal_code']) : '';
        $customer->country = Country::DEFAULT_COUNTRY;

        $customer->type = Users::TYPE_CUSTOMER;
        $customer->status = Users::STATUS_ACTIVE;
        $customer->date_created = time();

        //gen new random password
        $newPwd = Utils::genRandomString();
        $customer->new_pass = $newPwd;

        if ($customer->save()) {
            $customer->completeCreateUser();
            try {
                // send email to new user
                MyEmail::sendToNewUser($customer, $newPwd);
            } catch (Exception $exc) {
                
            }
        }

        return $customer;
    }

    /**
     * @HIEP : dien giup toi key result vao nhe
     */
    public function createPayment() {
        $payment = $this->result;

        //transaction
        $transaction = $payment->getTransactions();

        $related_source = $transaction[0]->getRelated_resources();

        //get object Sale
        $sale = $related_source[0]->getSale();

        $transaction_id = $sale->getId();

        $amount_obj = $sale->getAmount();

        $amount = $amount_obj->getTotal();


        $payment_key = $sale->getParentPayment();

        $payment_model = new Payment();
        $payment_model->payment_key = $payment_key;
        $payment_model->payment_date = time(); // se cap nhat sau
        $payment_model->method = Payment::METHOD_PAYPAL;
        $payment_model->transaction_id = $transaction_id;
        $payment_model->order_id = $this->order_id;
        $payment_model->amount = $amount;
        $payment_model->name = $this->service->s_name;
        $payment_model->type = Payment::TYPE_APPOINT;

        if ($payment_model->save()) {
            $service = $this->service;

            $hot_deal = Hotdeal::model()->find('sid=' . $service->sid);

            //day_of_week booking
            $date = '';
            if (isset($_GET['date'])) {

                $time_stamp = strtotime(str_replace('/', '-', urldecode($_GET['date'])));

                $t = new DateTime();
                $t->setTimestamp($time_stamp);
                $t->setTime(0, 0, 0);

                $date = $t->getTimestamp();
            }
            $day_of_week = date('w', $date);

            //convert 14:00 to 02:00 PM
            $time = strtotime($this->start_time);
            $discount = FALSE;

            $hotdeal_priod = HotdealPeriod::model()->findAll('hotdeal_id=:hotdeal_id AND day_of_week=:dayofweek', array(
                ':hotdeal_id' => $hot_deal->id,
                ':dayofweek' => $day_of_week,
            ));

            if ($hotdeal_priod) {
                foreach ($hotdeal_priod as $value) {
                    if (($time <= strtotime($value->end_time)) AND ( $time >= strtotime($value->start_time))) {
                        $discount = $value->discount;
                        break;
                    }
                }
            }

            // creating receipt
            $receipt = new Receipt();
            $receipt->order_id = $payment_model->order_id;
            $receipt->receipt_date = time();
            $receipt->final_price = $amount;
            $receipt->item_description = 't';
            $receipt->list_price = $amount;
            $receipt->discount = ($discount) ? $discount : 0;
            $receipt->discount_type = '%';
            $receipt->qty = 1;
            $receipt->tax = 0.0;

            if ($receipt->save()) {
                $receipt->receipt_key = $receipt->genReceiptKey();

                $receipt->update(array('receipt_key'));

                $this->redirect(Yii::app()->baseUrl . '/frontend/booking/success');
            } else {
                MyEmail::send_error('Cannot save receipt'); 
            }
        }
    }

    /**
     * Dùng cho trường hợp thanh toán qua paypal
     * payment via paypal successfully, will call this function
     */
    public function createAppt() {
        $data = PaypalPayment::model()->check_hot_deals($this->service->sid, urldecode($_GET['date']), urldecode($_GET['staff_time']));

        $staff_time = urldecode($_GET['staff_time']);
        $separatedData = explode('_', $staff_time);
        $staff_id = $separatedData[0];
        $time = $separatedData[1];

        $this->start_time = ltrim($time, '0');

        $appointment = new Appoint();

        $appointment->category_id = $this->service->category_id;
        $appointment->service_id = $this->service->sid;
        $appointment->note = urldecode($_GET['note']);
        $appointment->date = Utils::formatTime(str_replace('/', '-', urldecode($_GET['date']))); //format to 0 hour, 0 minute, 0 second
        $appointment->start_time = ltrim($time, '0');
        $appointment->end_time = Utils::plusminute($time, $this->service->duration, $this->service->recover);
        $appointment->isbackend = Appoint::BOOKING_ONLINE;
        $appointment->author_id = $staff_id;
        $appointment->type = Appoint::TYPE_APPOINTMENT;
        $appointment->status = Appoint::STATUS_COMPLETED_webmaster;
        $appointment->endby_original = time();
        $appointment->repeat_days = '';


        if ($appointment->save(FALSE)) {
            // Gán Appointment với Customer
            $apt_cus = new AptCustomer();
            $apt_cus->apt_id = $appointment->apt_id;
            $apt_cus->customer_id = $this->cus_id;
            $apt_cus->send_email = AptCustomer::SEND_EMAIL_DISABLE;
            $apt_cus->check_status = AptCustomer::CHECK_STATUS_DEFAULT;

            if ($appointment->service->user->business->is_pos == Business::IS_POS) {//Check Biz use POS
//                try
//                {
                $this->order_id = Orders::createOrder($appointment->apt_id, $this->cus_id, Orders::STATUS_COMPLETED_webmaster, 0, TRUE);

                if (!empty($data) AND $this->order_id) {
                    $dis_count = number_format(($data['price'] * $data['discount']) / 100, 2);
                    $final_price = number_format($data['price'] - $dis_count, 2);
                    $dis_count = number_format($dis_count, 2) . ' (' . $data['discount'] . '%' . ')';

                    $receipt = new Receipt();
                    $receipt->order_id = $this->order_id;
                    $receipt->discount_type = '%';
                    $receipt->final_price = $final_price;
                    $receipt->tax = 0.00;
                    $receipt->qty = 1;
                    $receipt->receipt_date = time();
                    $receipt->list_price = $data['price'];
                    $receipt->discount = $data['discount'];
                    $receipt->item_description = $this->service->description;

                    if ($receipt->validate() AND $receipt->save()) {

                        //send email to customer
                        MyEmail::send_email_confirmed_to_customer($appointment, $apt_cus->customer, FALSE, $dis_count, $final_price);
                        MyEmail::send_email_confirmed_to_staff($appointment, $apt_cus->customer, FALSE, $dis_count, $final_price);
                        MyEmail::send_email_confirmed_to_merchant($appointment, $apt_cus->customer, FALSE, $dis_count, $final_price);
                    }
                }
//                }catch (){
//                    
//                }
            }

            if ($apt_cus->validate() && $apt_cus->save()) {

                if ($this->cus_email) {
                    if (!$this->cus_model) {
                        MyEmail::send_error('can not find cus_model');
                    }

                    try {
                        //send email to customer
                        //send email to staff
                        //send email to merchant
                    } catch (Exception $exc) {
                        MyEmail::send_error('can not send email');
                    }
                } else {
                    MyEmail::send_error('can not find cus_model' . $this->cus_email);
                }
                return TRUE;
            } else {
                MyEmail::send_error('can not save apt_cus BookingController Line: 815');
                return FALSE;
            }
        } else {
            MyEmail::send_error('can not save appoinmnet BookingController Line: 820');

            return FALSE;
        }
    }

    /**
     * When customer choose payment via card or direct link to paypal, 
     * this action will be call
     * create a new appoinment
     * @return type
     */
    public function actionCreateAppt() {
        $data = PaypalPayment::model()->checkHotDeals();

        if (count($data) > 0) {

            $paypal = new Paypal;
            $paypal->currency = 'SGD';
            $paypal->data = $data;
            $pay_type = isset($_POST['pay_type']) ? $_POST['pay_type'] : 2; //1: Credit Card, 2:Redirect
            if ($pay_type == 1) { //day la credit card
                $paypal->actionPay();
                if ($paypal->status != 'ok') {
                    echo json_encode(array('status' => $paypal->status));
                    Yii::app()->end();
                } else {
                    //create 

                    $this->create_appoinmnet();
                }
            } else if ($pay_type == 2) {
                //redirect to paypal.com
                $paypal->actionRedirectPaypal();
                $redirect_url = $paypal->redirectUrl;

                if ($paypal->status == '')
                    $this->redirect($redirect_url);

                echo json_encode(array('status' => $paypal->status, 'url' => $redirect_url));
                Yii::app()->end();
            }
        }
        //service id;
        $s_id = $_POST['sid'];
        $service = Service::getRecordbySid($s_id);

        //customer id
        $cus_id = null;

        if (Yii::app()->user->isGuest) {
            //check customer by email
            $cus = Users::check_exist_by_email($_POST['email'], Users::TYPE_CUSTOMER);

            //if user exited in tbl_user
            if ($cus != NULL) {

                //kiem tra xem user co thuoc biz khong
                $check_cus_biz = Customer::checkCustomerBelongToBiz($cus->id, $service->biz->id);

                //neu customer la khach hang cua biz
                //lay id cua customer
                if ($check_cus_biz) {
                    $cus_id = $check_cus_biz->id;
                } else {

                    $new_cus = $this->createCustomerBiz($cus->id, $service->biz->id);
                    $cus_id = $new_cus->id;
                }
            } else { //if email not exited in tbl_user
                //create new user in
                $user = $this->createNewUser();

//create new customer in tbl_customer
                $new_cus = $this->createCustomerBiz($user->id, $service->biz->id);
                $cus_id = $new_cus->id;
            }
        }
        //update Customer
        else {

            $customer = Users::model()->findByPk(Yii::app()->user->getId());
            $customer->firstname = $_POST['fname'];
            $customer->lastname = $_POST['lname'];
//            $customer->email = $_POST['email'];
            $customer->mobile_phone = $_POST['phone'];
            $customer->occupation = $_POST['occupation'];
            $birthday = ($_POST['birthday'] != '') ? str_replace('/', '-', $_POST['birthday']) : NULL;
            $customer->birthday = strtotime($birthday);
            $customer->save();

            //kiem tra customer hien tai  co thuoc biz khong?
            $check_cus_biz = Customer::checkCustomerBelongToBiz($customer->id, $service->biz->id);

            if ($check_cus_biz != NULL) {
                $cus_id = $check_cus_biz->id;
            } else {
                $new_cus = $this->createCustomerBiz(Yii::app()->user->getId(), $service->biz->id);
                $cus_id = $new_cus->id;
            }
        }


        // Tạo Appointment
        $staff_time = $_POST['staff_time'];
        $separatedData = explode('_', $staff_time);
        $staff_id = $separatedData[0];

        if (FALSE == is_numeric($staff_id)) {
            echo json_encode(array(
                'status' => 'err'
            ));

            MyEmail::send_error('error empay staff id at BookingController, line 950. service_id:' . $s_id . '--staff_time' . $staff_time);


            Yii::app()->end();
        }

        $time = $separatedData[1];

        $appointment = new Appoint();
        $appointment->category_id = $service->category_id;
        $appointment->service_id = $s_id;
        $appointment->note = $_POST['note'];
        $appointment->date = strtotime(str_replace('/', '-', $_POST['date']));
        $appointment->start_time = ltrim($time, '0');
        $appointment->end_time = Utils::plusminute($time, $service->duration, $service->recover);
        $appointment->isbackend = Appoint::BOOKING_ONLINE;
        $appointment->author_id = $staff_id;
        $appointment->type = Appoint::TYPE_APPOINTMENT;
        $appointment->status = Appoint::BOOKING_STATUS_PENDING;


        if ($appointment->save() && $appointment->validate()) {
            // Gán Appointment với Customer
            $apt_cus = new AptCustomer();
            $apt_cus->apt_id = $appointment->apt_id;
            $apt_cus->customer_id = $cus_id;
            $apt_cus->send_email = AptCustomer::SEND_EMAIL_DISABLE;
            $apt_cus->check_status = AptCustomer::CHECK_STATUS_DEFAULT;


            if ($apt_cus->validate() && $apt_cus->save()) {
                try {
                    EmailConfirm::send($apt_cus->customer->user->email, $apt_cus->customer->user->name, $appointment, $apt_cus->customer);
                } catch (Exception $ex) {
                    MyEmail::send_error('can not send email BookingController.php line 975, id apt_cus' . $apt_cus->id);
                }

                echo json_encode(array(
                    'status' => 'ok',
                    'cus_email' => $apt_cus->customer->getEmail(),
                    'cus_name' => $apt_cus->customer->name,
                    'cus_key' => $apt_cus->customer->ckey,
                    'apt_id' => $apt_cus->apt_id,
                ));
                Yii::app()->end();
            } else {
                echo json_encode(array(
                    'status' => 'err'
                ));
                Yii::app()->end();
            }
        } else {
            echo json_encode(array(
                'status' => 'err'
            ));
            Yii::app()->end();
        }
    }

    public function create_appoinmnet() {
        //        date:24/Jul/2014
        //staff_time:7_09:45
        //fname:Nguyễn
        //lname:Anh Đức
        //email:anhduc.bkhn@gmail.com
        //phone:65432
        //occupation:Guru at webmaster
        //address:477 Minh Khai
        //postal_code:477 minh Khai
        //birthday:30/Jun/2014
        //note:
        //sid:15
        $staff_time = $_POST['staff_time'];
        $separatedData = explode('_', $staff_time);
        $staff_id = $separatedData[0];
        $time = $separatedData[1];

        $s_id = $_POST['sid'];
        $service = Service::getRecordbySid($s_id);

        if (Yii::app()->user->isGuest) {
            //check customer by email
            $cus = Users::check_exist_by_email($_POST['email'], Users::TYPE_CUSTOMER);

            //if user exited in tbl_user
            if ($cus != NULL) {

                //kiem tra xem user co thuoc biz khong
                $check_cus_biz = Customer::checkCustomerBelongToBiz($cus->id, $service->biz->id);

                //neu customer la khach hang cua biz
                //lay id cua customer
                if ($check_cus_biz) {
                    $cus_id = $check_cus_biz->id;
                } else {

                    $new_cus = $this->createCustomerBiz($cus->id, $service->biz->id);
                    $cus_id = $new_cus->id;
                }
            } else { //if email not exited in tbl_user
                //create new user in
                $user = $this->createNewUser();

//create new customer in tbl_customer
                $new_cus = $this->createCustomerBiz($user->id, $service->biz->id);
                $cus_id = $new_cus->id;
            }
        }
        //update Customer
        else {
            /**
             * @webmaster_TODO
             * update to tbl_users too
             */
            $customer = Users::model()->findByPk(Yii::app()->user->getId());
            $customer->firstname = $_POST['fname'];
            $customer->lastname = $_POST['lname'];
//            $customer->email = $_POST['email'];
            $customer->mobile_phone = $_POST['phone'];
            $customer->occupation = $_POST['occupation'];
            $birthday = ($_POST['birthday'] != '') ? str_replace('/', '-', $_POST['birthday']) : NULL;
            $customer->birthday = strtotime($birthday);
            $customer->save();

//kiem tra customer hien tai  co thuoc biz khong?
            $check_cus_biz = Customer::checkCustomerBelongToBiz($customer->id, $service->biz->id);

            if ($check_cus_biz != NULL) {
                $cus_id = $check_cus_biz->id;
            } else {
                $new_cus = $this->createCustomerBiz(Yii::app()->user->getId(), $service->biz->id);
                $cus_id = $new_cus->id;
            }
        }

        $appt = new Appoint();
        $appt->status = Appoint::STATUS_COMPLETED_webmaster;
        $appt->author_id = $staff_id;
        $appt->start_time = $time;
        $appt->end_time = Utils::plusminute($time, $service->duration, $service->recover);
        $appt->date = strtotime(str_replace('/', '-', $_POST['date']));
        $appt->type = Appoint::TYPE_APPOINTMENT;
        $appt->isbackend = Appoint::BOOKING_ONLINE;
        $appt->note = $_POST['note'];
        $appt->service_id = $s_id;
        $appt->category_id = $service->category_id;

        if ($appt->save() && $appt->validate()) {
            // Gán Appointment với Customer
            $apt_cus = new AptCustomer();
            $apt_cus->apt_id = $appt->apt_id;
            $apt_cus->customer_id = $cus_id;
            $apt_cus->send_email = AptCustomer::SEND_EMAIL_DISABLE;
            $apt_cus->check_status = AptCustomer::CHECK_STATUS_DEFAULT;


            if ($apt_cus->validate() && $apt_cus->save()) {
                $data = PaypalPayment::model()->check_hot_deals($s_id, $_POST['date'], $_POST['staff_time']);
                try {

                    if ($appt->service->user->business->is_pos == Business::IS_POS) {//Check Biz use POS
//                try
//                {
                        $this->order_id = Orders::createOrder($appt->apt_id, $this->cus_id, Orders::STATUS_COMPLETED_webmaster, 0, TRUE);

                        if (!empty($data) AND $this->order_id) {
                            $dis_count = number_format(($data['price'] * $data['discount']) / 100, 2);
                            $final_price = number_format($data['price'] - $dis_count, 2);
                            $dis_count = number_format($dis_count, 2) . ' (' . $data['discount'] . '%' . ')';

                            $receipt = new Receipt();
                            $receipt->order_id = $this->order_id;
                            $receipt->discount_type = '%';
                            $receipt->final_price = $final_price;
                            $receipt->tax = 0.00;
                            $receipt->qty = 1;
                            $receipt->receipt_date = time();
                            $receipt->list_price = $data['price'];
                            $receipt->discount = $data['discount'];
                            $receipt->item_description = $service->description;

                            if ($receipt->validate() AND $receipt->save()) {

                                //send email to customer
                                MyEmail::send_email_confirmed_to_customer($appt, $apt_cus->customer, FALSE, $dis_count, $final_price);
                                MyEmail::send_email_confirmed_to_staff($appt, $apt_cus->customer, FALSE, $dis_count, $final_price);
                                MyEmail::send_email_confirmed_to_merchant($appt, $apt_cus->customer, FALSE, $dis_count, $final_price);
                            }
                        }
//                }catch (){
//                    
//                }
                    }
                } catch (Exception $ex) {
                    MyEmail::send_error('can not send email BookingController.php line 975, id apt_cus' . $apt_cus->id);
                }

                echo json_encode(array(
                    'status' => 'ok',
                    'cus_email' => $apt_cus->customer->user->email,
                    'cus_name' => $apt_cus->customer->user->getName(),
                    'cus_key' => $apt_cus->customer->ckey,
                    'apt_id' => $apt_cus->apt_id,
                ));
                Yii::app()->end();
            } else {
                echo json_encode(array(
                    'status' => 'err'
                ));
                Yii::app()->end();
            }
        } else {
            echo json_encode(array(
                'status' => 'err'
            ));
            Yii::app()->end();
        }
    }

    public function actionCreateRoom() {
//service id
        $s_id = $_POST['sid'];
        $service = Service::getRecordbySid($s_id);

//customer id
        $cus_id = null;
        //customer email
        $cus_email = null;

//create Customer
        if (Yii::app()->user->isGuest) {
//check customer by email
            $cus = Users::check_exist_by_email($_POST['email'], Users::TYPE_CUSTOMER);


            //if user exited in tbl_user
            if ($cus != NULL) {

//kiem tra xem user co thuoc biz khong
                $check_cus_biz = Customer::checkCustomerBelongToBiz($cus->id, $service->biz->id);

//neu customer la khach hang cua biz
//lay id cua customer
                if ($check_cus_biz) {
                    $cus_id = $check_cus_biz->id;
                } else {

                    $new_cus = $this->createCustomerBiz($cus->id, $service->biz->id);
                    $cus_id = $new_cus->id;
                }
            } else { //if email not exited in tbl_user
                //create new user in
                $user = $this->createNewUser();

//create new customer in tbl_customer
                $new_cus = $this->createCustomerBiz($user->id, $service->biz->id);
                $cus_id = $new_cus->id;
            }
        }
        //update Customer
        else {
            $customer = Users::model()->findByPk(Yii::app()->user->getId());
            $customer->firstname = $_POST['fname'];
            $customer->lastname = $_POST['lname'];
//            $customer->email = $_POST['email'];
            $customer->mobile_phone = $_POST['phone'];
            $customer->occupation = $_POST['occupation'];
            $birthday = ($_POST['birthday'] != '') ? str_replace('/', '-', $_POST['birthday']) : NULL;
            $customer->birthday = strtotime($birthday);
            $customer->save();

//kiem tra customer hien tai  co thuoc biz khong?
            $check_cus_biz = Customer::checkCustomerBelongToBiz($customer->id, $service->biz->id);

            if ($check_cus_biz != NULL) {
                $cus_id = $check_cus_biz->id;
            } else {
                $new_cus = $this->createCustomerBiz(Yii::app()->user->getId(), $service->biz->id);
                $cus_id = $new_cus->id;
            }
        }

        // Gán Appointment với Customer
        $apt_cus = new AptCustomer();
        $apt_cus->apt_id = $_POST['apt_id'];
        $apt_cus->customer_id = $cus_id;
        $apt_cus->send_email = AptCustomer::SEND_EMAIL_ENABLE;
        $apt_cus->check_status = AptCustomer::CHECK_STATUS_DEFAULT;

        if ($apt_cus->validate() && $apt_cus->save()) {

            if (!$apt_cus->customer) {
//                MyEmail::send_error('BookingController line 1164:'.$apt_cus->id);  
            }

            if (!$apt_cus->customer->user) {
//                MyEmail::send_error('');  
            }

            if (!$apt_cus->customer->user->name) {
//                MyEmail::send_error('BookingConamentroller line 1172: '.$apt_cus->id);  
            }


            EmailConfirm::send($apt_cus->customer->user->email, $apt_cus->customer->user->name, $apt_cus->appt, $apt_cus->customer);

            echo json_encode(array(
                'status' => 'ok',
                'cus_email' => $apt_cus->customer->getEmail(),
                'cus_name' => $apt_cus->customer->name,
                'cus_key' => $apt_cus->customer->ckey,
                'apt_id' => $apt_cus->apt_id,
            ));

            Yii::app()->end();
        } else {
            echo json_encode(array(
                'status' => 'err'
            ));
            Yii::app()->end();
        }
    }

    public function actionResendEmail() {
        if (isset($_POST['trial'])) {
            $appoint = TrialAppoint::model()->findByPk($_POST['apt_id']);
            if ($appoint->status == Appoint::BOOKING_STATUS_CONFIRM) {
                echo json_encode(array(
                    'status' => 2
                ));
            } else {
                echo json_encode(array(
                    'status' => 1
                ));

                $appt = Appoint::model()->findByPk($_POST['apt_id']);
                $cus = Customer::model()->findByAttributes(array('cus_key' => $_POST['cus_key']));
                try {
                    EmailConfirm::send($_POST['cus_email'], $_POST['cus_name'], $appt, $cus, TRUE);
                } catch (Exception $ex) {
                    
                }
            }
        } else {
            $appoint = Appoint::getRecordByID($_POST['apt_id']);
            $cus = Customer::model()->findByAttributes(array('ckey' => $_POST['cus_key']));
            if ($appoint->status == Appoint::BOOKING_STATUS_CONFIRM) {
                echo json_encode(array(
                    'status' => 2
                ));
            } else {
                echo json_encode(array(
                    'status' => 1
                ));
                try {
                    EmailConfirm::send($_POST['cus_email'], $_POST[
                            'cus_name'], $appoint, $cus);
                } catch (Exception $ex) {
                    
                }
            }
        }
        Yii::app()->end();
    }

    public function actionConfirm() {
        if (empty($_GET)) {
            Yii::app()->user->setFlash('error', Yii::t('frontend','Something wrong or time expired!'));
        }

        $appoint = Appoint::getRecordByID($_GET['appoint']);
        $service = FALSE;
        $customer = FALSE;
//if appoint not found
        if (!$appoint) {
            Yii::app()->user->setFlash('error', Yii::t('frontend','Something wrong!'));
        } else {
//if appoint has been confirmed
            if ($appoint->status == Appoint::BOOKING_STATUS_CONFIRM) {
                Yii::app()->user->setFlash('success', Yii::t('frontend','Your reservation has been confirmed.'));
            } else {
                $customer = Customer::getRecordByCkey($_GET['ckey']);
                if (!$customer) {
                    Yii::app()->user->setFlash('error', Yii::t('frontend','Something wrong'));
                } else {
                    $crite = new CDbCriteria();
                    $crite->compare('emai', $customer->email);
                    $crite->compare('code', $_GET['code']);
                    $crite->compare('type', EmailConfirm::TYPE_BOOKING);

                    $crite->addCondition('expire > ' . time());

                    $confirm = EmailConfirm::model()->find($crite);

                    if (!$confirm) {
                        Yii::app()->user->setFlash('success', Yii::t('frontend','Your reservation has been confirmed.'));
                    } else {
                        $appoint->status = Appoint::BOOKING_STATUS_CONFIRM;

                        if ($appoint->update(array('status'))) {
                            Yii::app()->user->setFlash('success', Yii::t('frontend','Your reservation has been confirmed.'));

                            Orders::createOrder($appoint->apt_id, $customer->id, Orders::STATUS_PENDING, 0, FALSE);

//send mail order confirm
                            $isc_file = Helper::createICSFile($appoint, $customer);
                            MyEmail::NewAppointToCus($appoint, $customer, $isc_file);
                            MyEmail::NewAppointToBiz($appoint, $customer, $isc_file);
                            MyEmail::NewAppointToStaff($appoint, $customer, $isc_file);

                            $confirm->delete();
                        }
                    }
                }
            }
        }

        $this->render('confirm', array
            (
            'appoint' => $appoint,
            'customer' => $customer
        ));
    }

    /**
     * create new record in tbl_customer
     */
    private function createCustomerBiz($user_id, $biz_id) {
        $new_cus = new Customer();

        $new_cus->status = Customer::STATUS_ACTIVE;

        $new_cus->biz_id = $biz_id;

        $new_cus->user_id = $user_id;

        if ($new_cus->save()) {
            $new_cus->updateCkey();

            return $new_cus;
        } else {
            return FALSE;
        }
    }

    /**
     * create a new customer
     * @return Cactiverecord a signle active record
     */
    private function createNewUser() {
        $customer = new CustomerBookForm();
        $customer->firstname = $_POST['fname'];
        $customer->lastname = $_POST ['lname'];
        $customer->email = $_POST['email'];
        $customer->mobile_phone = $_POST['phone'];
        $customer->occupation = $_POST['occupation'];
        $birthday = ($_POST['birthday'] != '') ? str_replace('/', '-', $_POST['birthday']) : NULL;
        $customer->birthday = strtotime($birthday);
        $customer->address = $_POST['address'];
        $customer->postal_code = $_POST['postal_code'];
        $customer->country = Country::DEFAULT_COUNTRY;

        $customer->type = Users::TYPE_CUSTOMER;
        $customer->status = Users::STATUS_ACTIVE;
        $customer->date_created = time();

//gen new random password
        $newPwd = Utils::genRandomString();
        $customer->new_pass = $newPwd;

        if ($customer->save()) {
            $customer->completeCreateUser();
        }

        try {

            MyEmail::sendToNewUser($customer, $newPwd);
        } catch (Exception $exc) {
            
        }

        // send email to new user



        return $customer;
    }

    public function actionGetServiceDuration() {
        if (isset($_GET['service_id'])) {
            $service = Service::model()->findByPk($_GET['service_id']);
            if ($service != null) {
                echo json_encode(array(
                    'duration' => $service->duration,
                    'recover' => $service->recover,
                ));
                Yii::app()->end();
            }
        }
    }

    public function actionGetStaffFreetime() {
        //English textual 28/Dec/2013
        $date = strtotime(str_replace('/', '-', $_POST['date']));


        $sid = $_POST['sid'];
        $staff_id = $_POST['staff'];
        $service = Service::getRecordbySid($sid);

        //Biz work time in this date
        $work_day = $service->user->business->work_day;
        $biz_opentime = $service->user->business->open_time;


//lay gio lam viec trong ngay
        $biz_work_times = Business::getWorkTimesByDay($date, $work_day);


        //neu null thi return
        if ($biz_work_times == NULL) {
            echo json_encode(array(
                'morning' => array(),
                'afternoon' => array(),
                'evening' => array(),
            ));

            Yii::app()->end();
        }


        $arr_staff_time = $this->_getFreetime($staff_id, $date, $sid, $biz_work_times, $biz_opentime);

        echo json_encode($arr_staff_time);
        Yii::app()->end();
    }

    public function actionRendercalendar() {
        if (Yii::app()->request->isAjaxRequest) {

            //find service model
            $service = Service::model()->findByPk($_POST['sid']);

            $biz_dayofff = $service->user->business->listDayOff;
            $closeday = $service->user->business->closeday;
            $openday = $service->user->business->openday;
            $disable_day = array();
            $curr_date = date('Y-m-d', time());

            $chedules = SchedulesUser::model()->findAll('date >=:curr_date AND user_id=:userid AND type<>:type ', array(':curr_date' => $curr_date,
                ':userid' => $_POST['staff_id'],
                ':type' => 1
            ));

            if ($chedules != NULL) {
                foreach ($chedules as $value) {
                    $disable_day[] = $value->date;
                }
            }

            echo json_encode(
                    array(
                        'biz_dayoff' => $biz_dayofff,
                        'closeday' => $closeday,
                        'openday' => $openday,
                        'disable_day' => $disable_day
                    )
            );

            Yii::app()->end();
        }
    }

    /**
     * 
     * @param int $staff staff id
     * @param string $date date time, English textual 28/Dec/2013
     * @param int $sid service id
     * @param string $biz_work_times Business work_time in this day
     * @param integer $biz_opentime Business open_time
     * @return mixed List of avaiable time of staff
     */
    private function _getFreetime($staff, $date, $sid, $biz_work_times, $biz_opentime) {
        $arr_staff_time = array();
        $result_arr = array();
        $arr_staff_time_morning = array();
        $arr_staff_time_afternoon = array();
        $arr_staff_time_evening = array();

        $service = Service::model()->findByPk($sid);
        $_cover_time = $service->totalTime; // interger

        $_cover_time_inSecond = $_cover_time * 60;

        $result_arr_morning = array();
        $result_arr_afternoon = array();
        $result_arr_evening = array();

        //Nếu không select staff
        if ($staff == 0) {
            //find all staff
            $service_staffs = ServiceStaff::model()->findAll('sid=:sid', array(':sid' => $sid));


            if ($service_staffs) {
                foreach ($service_staffs as $service_staff) {
                    $staff_id = Users::getIdByUkey($service_staff->sukey);

                    if (FALSE == $staff_id) {
                        MyEmail::send_error('Not found staff at BookingController line 1491. staff_ukey:' . $service_staff->sukey);
                        break;
                    }

                    $appoint = Appoint::model()->findAll('date=:date AND author_id=:author_id', array(
                        ':date' => $date,
                        ':author_id' => $staff_id
                    ));


                    //Business Worktime on this day
                    $morning = Business::getMinutesStepbyDay(Utils::MORNING, $biz_work_times, $date, $biz_opentime, $_cover_time_inSecond);
                    $afternoon = Business::getMinutesStepbyDay(Utils::AFTERNOON, $biz_work_times, $date, $biz_opentime, $_cover_time_inSecond);
                    $evening = Business::getMinutesStepbyDay(Utils::EVENING, $biz_work_times, $date, $biz_opentime, $_cover_time_inSecond);

                    $arr = array(
                        'morning' => $morning,
                        'afternoon' => $afternoon,
                        'evening' => $evening
                    );

                    /*
                     * Nếu không có appoint nào trong ngày thì Staff free-time cả ngày
                     */
                    if ($appoint == NULL) {

                        $result_arr_morning = array();

                        foreach ($arr['morning'] as $v) {
                            $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $v);
                            if (Yii::app()->user->isGuest && isset(Yii::app()->session['email_has_1stdiscount']) && !empty(Yii::app()->session['email_has_1stdiscount']) && Customer::email_is_firsttime_with_merchant(Yii::app()->session['email_has_1stdiscount'], $service->author_id))
                                $the_first = Thefirst::getDiscountByTime($sid, $date, $v, FALSE);
                            else
                                $the_first = Thefirst::getDiscountByTime($sid, $date, $v);
                            if ($discount_by_time || $the_first) {
                                $result_arr_morning[] = array(
                                    'value' => $staff_id . '_' . $v,
                                    'time' => $v,
                                    'discount' => $discount_by_time,
                                    '1st'=>$the_first
                                    );
                            }
                            else {
                                $result_arr_morning[] = array(
                                    'value' => $staff_id . '_' . $v,
                                    'time' => $v);
                            }
                        }
                        $result_arr_afternoon = array();
                        foreach ($arr['afternoon'] as $v) {
                            $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $v);
                            if (Yii::app()->user->isGuest && isset(Yii::app()->session['email_has_1stdiscount']) && !empty(Yii::app()->session['email_has_1stdiscount']) && Customer::email_is_firsttime_with_merchant(Yii::app()->session['email_has_1stdiscount'], $service->author_id))
                                $the_first = Thefirst::getDiscountByTime($sid, $date, $v, FALSE);
                            else
                                $the_first = Thefirst::getDiscountByTime($sid, $date, $v);
                            if ($discount_by_time||$the_first) {
                                $result_arr_afternoon[] = array(
                                    'value' => $staff_id . '_' . $v,
                                    'time' => $v,
                                    'discount' => $discount_by_time,
                                    '1st'=>$the_first);
                            } else {
                                $result_arr_afternoon[] = array(
                                    'value' => $staff_id . '_' . $v,
                                    'time' => $v);
                            }
                        }
                        $result_arr_evening = array();
                        foreach ($arr['evening'] as $v) {
                            $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $v);
                            if (Yii::app()->user->isGuest && isset(Yii::app()->session['email_has_1stdiscount']) && !empty(Yii::app()->session['email_has_1stdiscount']) && Customer::email_is_firsttime_with_merchant(Yii::app()->session['email_has_1stdiscount'], $service->author_id))
                                $the_first = Thefirst::getDiscountByTime($sid, $date, $v, FALSE);
                            else
                                $the_first = Thefirst::getDiscountByTime($sid, $date, $v);
                            if ($discount_by_time||$the_first) {
                                $result_arr_evening[] = array(
                                    'value' => $staff_id . '_' . $v,
                                    'time' => $v,
                                    'discount' => $discount_by_time,
                                    '1st'=>$the_first);
                            } else {
                                $result_arr_evening[] = array(
                                    'value' => $staff_id . '_' . $v,
                                    'time' => $v);
                            }
                        }

                        $result_arr['morning'] = $result_arr_morning;
                        $result_arr['afternoon'] = $result_arr_afternoon;
                        $result_arr['evening'] = $result_arr_evening;

                        echo json_encode($result_arr);
                        Yii::app()->end();
                    } else {

                        $busy_array = $this->_getBusyTime($appoint, $service);
                        foreach ($busy_array as $busy_time) {
                            //remove busy time
                            $morning_busy = array_search($busy_time, $morning);
                            $afternoon_busy = array_search($busy_time, $afternoon);
                            $evening_busy = array_search($busy_time, $evening);
                            if ($morning_busy !== FALSE) {
                                unset($morning[$morning_busy]);
                            }
                            if ($afternoon_busy !== FALSE) {
                                unset($afternoon[$afternoon_busy]);
                            }
                            if ($evening_busy !== FALSE) {
                                unset($evening[$evening_busy]);
                            }
                        }
                        /*
                         * Viết lại array
                         */
                        $result_arr = array();
                        $result_arr_morning = array();
                        foreach ($morning as $v) {
                            $result_arr_morning[] = $v;
                        }

                        $result_arr_afternoon = array();

                        foreach ($afternoon as $v) {
                            $result_arr_afternoon[] = $v;
                        }
                        $result_arr_evening = array();
                        foreach ($evening as $v) {
                            $result_arr_evening[] = $v;
                        }


                        $result_arr['morning'] = $result_arr_morning;
                        $result_arr['afternoon'] = $result_arr_afternoon;
                        $result_arr['evening'] = $result_arr_evening;
                    }
//rewrite array: time=>staff
                    foreach ($result_arr['morning'] as $v) {
                        $arr_staff_time_morning[$v] = $staff_id;
                    }

                    foreach ($result_arr['afternoon'] as $v) {
                        $arr_staff_time_afternoon[$v] = $staff_id;
                    }

                    foreach ($result_arr['evening'] as $v) {
                        $arr_staff_time_evening[$v] = $staff_id;
                    }
                }
            }
//sort time by key
            ksort($arr_staff_time_morning);
            ksort($arr_staff_time_afternoon);
            ksort($arr_staff_time_evening);

            $arr_staff_time = array(
                'morning' => $arr_staff_time_morning,
                'afternoon' => $arr_staff_time_afternoon,
                'evening' => $arr_staff_time_evening
            );

            $arr_morning = array();

            foreach ($arr_staff_time['morning'] as $time => $staff_id) {
                $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $time);
                if (Yii::app()->user->isGuest && isset(Yii::app()->session['email_has_1stdiscount']) && !empty(Yii::app()->session['email_has_1stdiscount']) && Customer::email_is_firsttime_with_merchant(Yii::app()->session['email_has_1stdiscount'], $service->author_id))
                    $the_first = Thefirst::getDiscountByTime($sid, $date, $time, FALSE);
                else
                    $the_first = Thefirst::getDiscountByTime($sid, $date, $time);
                if ($discount_by_time||$the_first) {
                    $arr_morning[] = array(
                        'value' => $staff_id . '_' . $time,
                        'time' => $time,
                        'discount' => $discount_by_time,
                        '1st'=>$the_first);
                } else {
                    $arr_morning[] = array(
                        'value' => $staff_id . '_' . $time,
                        'time' => $time);
                }
            }
            $arr_afternoon = array();
            foreach ($arr_staff_time['afternoon'] as $time => $staff_id) {
                $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $time);
                if (Yii::app()->user->isGuest && isset(Yii::app()->session['email_has_1stdiscount']) && !empty(Yii::app()->session['email_has_1stdiscount']) && Customer::email_is_firsttime_with_merchant(Yii::app()->session['email_has_1stdiscount'], $service->author_id))
                    $the_first = Thefirst::getDiscountByTime($sid, $date, $time, FALSE);
                else
                    $the_first = Thefirst::getDiscountByTime($sid, $date, $time);
                if ($discount_by_time||$the_first) {
                    $arr_afternoon[] = array(
                        'value' => $staff_id . '_' . $time,
                        'time' => $time,
                        'discount' => $discount_by_time,
                        '1st'=>$the_first);
                } else {
                    $arr_afternoon[] = array(
                        'value' => $staff_id . '_' . $time,
                        'time' => $time);
                }
            }
            $arr_evening = array();



            foreach ($arr_staff_time['evening'] as $time => $staff_id) {
                $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $time);
                if (Yii::app()->user->isGuest && isset(Yii::app()->session['email_has_1stdiscount']) && !empty(Yii::app()->session['email_has_1stdiscount']) && Customer::email_is_firsttime_with_merchant(Yii::app()->session['email_has_1stdiscount'], $service->author_id))
                    $the_first = Thefirst::getDiscountByTime($sid, $date, $time, FALSE);
                else
                    $the_first = Thefirst::getDiscountByTime($sid, $date, $time);
                if ($discount_by_time||$the_first) {
                    $arr_evening[] = array(
                        'value' => $staff_id . '_' . $time,
                        'time' => $time,
                        'discount' => $discount_by_time,
                        '1st'=>$the_first);
                } else {
                    $arr_evening[] = array(
                        'value' => $staff_id . '_' . $time,
                        'time' => $time);
                }
            }
            $staff_time['morning'] = $arr_morning;
            $staff_time['afternoon'] = $arr_afternoon;
            $staff_time['evening'] = $arr_evening;

            echo json_encode($staff_time);
            Yii::app()->end();
        } else {
//Lấy các appoint theo staff đó
            $appoint = Appoint::model()->findAll('date=:date AND author_id=:author_id', array(':date' => $date, ':author_id' => $staff
            ));


//Business Worktimes on this day
            $morning = Business::getMinutesStepbyDay(Utils::MORNING, $biz_work_times, $date, $biz_opentime, $_cover_time_inSecond);
            $afternoon = Business::getMinutesStepbyDay(Utils::AFTERNOON, $biz_work_times, $date, $biz_opentime, $_cover_time_inSecond);
            $evening = Business::getMinutesStepbyDay(Utils::EVENING, $biz_work_times, $date, $biz_opentime, $_cover_time_inSecond);

            $arr = array('morning' => $morning, 'afternoon' => $afternoon, 'evening' => $evening);
            /*
             * Nếu không có appoint nào trong ngày thì Staff free-time cả ngày
             */
            if ($appoint == NULL) {
                $result_arr_morning = array();
                foreach ($arr['morning'] as $v) {
                    $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $v);
                    if (Yii::app()->user->isGuest && isset(Yii::app()->session['email_has_1stdiscount']) && !empty(Yii::app()->session['email_has_1stdiscount']) && Customer::email_is_firsttime_with_merchant(Yii::app()->session['email_has_1stdiscount'], $service->author_id))
                        $the_first = Thefirst::getDiscountByTime($sid, $date, $v, FALSE);
                    else
                        $the_first = Thefirst::getDiscountByTime($sid, $date, $v);
                    if ($discount_by_time||$the_first) {
                        $result_arr_morning[] = array(
                            'value' => $staff . '_' . $v,
                            'time' => $v,
                            'discount' => $discount_by_time,
                            '1st'=>$the_first);
                    } else {
                        $result_arr_morning[] = array('value' => $staff . '_' . $v,
                            'time' => $v);
                    }
                }
                $result_arr_afternoon = array();
                foreach ($arr['afternoon'] as $v) {
                    $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $v);
                    if (Yii::app()->user->isGuest && isset(Yii::app()->session['email_has_1stdiscount']) && !empty(Yii::app()->session['email_has_1stdiscount']) && Customer::email_is_firsttime_with_merchant(Yii::app()->session['email_has_1stdiscount'], $service->author_id))
                        $the_first = Thefirst::getDiscountByTime($sid, $date, $v, FALSE);
                    else
                        $the_first = Thefirst::getDiscountByTime($sid, $date, $v);
                    if ($discount_by_time||$the_first) {
                        $result_arr_afternoon[] = array(
                            'value' => $staff . '_' . $v,
                            'time' => $v,
                            'discount' => $discount_by_time,
                            '1st'=>$the_first);
                    } else {
                        $result_arr_afternoon[] = array('value' => $staff . '_' . $v,
                            'time' => $v);
                    }
                }
                $result_arr_evening = array();
                foreach ($arr['evening'] as $v) {
                    $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $v);
                    if (Yii::app()->user->isGuest && isset(Yii::app()->session['email_has_1stdiscount']) && !empty(Yii::app()->session['email_has_1stdiscount']) && Customer::email_is_firsttime_with_merchant(Yii::app()->session['email_has_1stdiscount'], $service->author_id))
                        $the_first = Thefirst::getDiscountByTime($sid, $date, $v, FALSE);
                    else
                        $the_first = Thefirst::getDiscountByTime($sid, $date, $v);
                    if ($discount_by_time||$the_first) {
                        $result_arr_evening[] = array(
                            'value' => $staff . '_' . $v,
                            'time' => $v,
                            'discount' => $discount_by_time,
                            '1st'=>$the_first);
                    } else {
                        $result_arr_evening[] = array(
                            'value' => $staff . '_' . $v,
                            'time' => $v);
                    }
                }
                $result_arr['morning'] = $result_arr_morning;
                $result_arr['afternoon'] = $result_arr_afternoon;
                $result_arr['evening'] = $result_arr_evening;

                echo json_encode($result_arr);
                Yii::app()->end();
            } else {
                $busy_array = $this->_getBusyTime($appoint, $service);
                foreach ($busy_array as $busy_time) {
//remove busy time
                    $morning_busy = array_search($busy_time, $morning);
                    $afternoon_busy = array_search($busy_time, $afternoon);
                    $evening_busy = array_search($busy_time, $evening);
                    if ($morning_busy !== FALSE) {
                        unset($morning[$morning_busy]);
                    }
                    if ($afternoon_busy !== FALSE) {
                        unset($afternoon[$afternoon_busy]);
                    }

                    if ($evening_busy !== FALSE) {
                        unset($evening[$evening_busy]);
                    }
                }
                foreach ($morning as $v) {
                    $result_arr_morning[] = $v;
                }
                foreach ($afternoon as $v) {
                    $result_arr_afternoon[] = $v;
                }
                foreach ($evening as $v) {
                    $result_arr_evening[] = $v;
                }
                $result_arr['morning'] = $result_arr_morning;
                $result_arr['afternoon'] = $result_arr_afternoon;
                $result_arr['evening'] = $result_arr_evening;

                //rewrite array: time=>staff
                foreach ($result_arr['morning'] as $v) {
                    $arr_staff_time_morning[$v] = $staff;
                }

                foreach ($result_arr['afternoon'] as $v) {
                    $arr_staff_time_afternoon[$v] = $staff;
                }
                foreach ($result_arr['evening'] as $v) {
                    $arr_staff_time_evening[$v] = $staff;
                }
//sort time
                ksort($arr_staff_time_morning);
                ksort($arr_staff_time_afternoon);
                ksort($arr_staff_time_evening);

                $arr_staff_time = array(
                    'morning' => $arr_staff_time_morning,
                    'afternoon' => $arr_staff_time_afternoon,
                    'evening' => $arr_staff_time_evening,
                );

                $arr_morning = array();

                foreach ($arr_staff_time['morning'] as $time => $staff) {
                    $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $time);
                    if (Yii::app()->user->isGuest && isset(Yii::app()->session['email_has_1stdiscount']) && !empty(Yii::app()->session['email_has_1stdiscount']) && Customer::email_is_firsttime_with_merchant(Yii::app()->session['email_has_1stdiscount'], $service->author_id))
                        $the_first = Thefirst::getDiscountByTime($sid, $date, $time, FALSE);
                    else
                        $the_first = Thefirst::getDiscountByTime($sid, $date, $time);
                    if ($discount_by_time||$the_first) {
                        $arr_morning[] = array(
                            'value' => $staff . '_' . $time,
                            'time' => $time,
                            'discount' => $discount_by_time,
                            '1st'=>$the_first);
                    } else {
                        $arr_morning[] = array(
                            'value' => $staff . '_' . $time,
                            'time' => $time);
                    }
                }

                $arr_afternoon = array();

                foreach ($arr_staff_time['afternoon'] as $time => $staff) {
                    $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $time);
                    if (Yii::app()->user->isGuest && isset(Yii::app()->session['email_has_1stdiscount']) && !empty(Yii::app()->session['email_has_1stdiscount']) && Customer::email_is_firsttime_with_merchant(Yii::app()->session['email_has_1stdiscount'], $service->author_id))
                        $the_first = Thefirst::getDiscountByTime($sid, $date, $time, FALSE);
                    else
                        $the_first = Thefirst::getDiscountByTime($sid, $date, $time);
                    if ($discount_by_time||$the_first) {
                        $arr_afternoon[] = array(
                            'value' => $staff . '_' . $time,
                            'time' => $time,
                            'discount' => $discount_by_time,
                            '1st'=>$the_first);
                    } else {
                        $arr_afternoon[] = array(
                            'value' => $staff . '_' . $time,
                            'time' => $time);
                    }
                }

                $arr_evening = array();

                foreach ($arr_staff_time['evening'] as $time => $staff) {
                    $discount_by_time = Hotdeal::getDiscountByTime($sid, $date, $time);
                    if (Yii::app()->user->isGuest && isset(Yii::app()->session['email_has_1stdiscount']) && !empty(Yii::app()->session['email_has_1stdiscount']) && Customer::email_is_firsttime_with_merchant(Yii::app()->session['email_has_1stdiscount'], $service->author_id))
                        $the_first = Thefirst::getDiscountByTime($sid, $date, $time, FALSE);
                    else
                        $the_first = Thefirst::getDiscountByTime($sid, $date, $time);
                    if ($discount_by_time||$the_first) {
                        $arr_evening[] = array(
                            'value' => $staff . '_' . $time,
                            'time' => $time,
                            'discount' => $discount_by_time,
                            '1st'=>$the_first);
                    } else {
                        $arr_evening[] = array(
                            'value' => $staff . '_' . $time,
                            'time' => $time);
                    }
                }
                $staff_time['morning'] = $arr_morning;
                $staff_time['afternoon'] = $arr_afternoon;
                $staff_time['evening'] = $arr_evening;

                echo json_encode($staff_time);
                Yii::app()->end();
            }
        }
    }

    private function _getBusyTime($appoint, $service) {
        $busy_merge = array();

        foreach ($appoint as $apt) {
//round recover
            $start_stamp = strtotime($apt->start_time) - (($service->recover + $service->duration) * 60);
            $start = date('G:i', $start_stamp);
            //list busy time
            /*
             * Thêm busy time tạo trong backend
             */
            $busy_times[] = Utils::minuteStep(5, $start, $apt->end_time, FALSE);
            foreach ($busy_times as $v) {
                $busy_merge = array_merge($v, $busy_merge);
            }
        }

//remove dup
        $busy_array = array_unique($busy_merge);
        return $busy_array;
    }

    public function actionRequestService() {
        if (!isset($_GET['mid'])) {
            throw new CHttpException(404, 'Not found merchant line: 1575');
        }

        $criteria = new CDbCriteria();
        $criteria->select = array('id,business_name,address,address2,business_description,business_logo,postal_code');
        $criteria->compare('id', $_GET['mid']);
        $criteria->compare('type', Users::TYPE_BUSINESS);
        $criteria->compare('status', Users::STATUS_BLOCK);

        $merchant = Users::model()->find($criteria);

        if (!$merchant) {
            throw new CHttpException(404, 'Not found merchant line');
        }

        if (Yii::app()->user->isGuest) {
            $customer = new Users();
            if (isset($_POST['ajax']) && $_POST['ajax'] === 'book-form') {
                echo CActiveForm::validate($customer);
                Yii::app()->end();
            }
        } else {
            $customer = Users::model()->findByPk(Yii::app()->user->id);
        }

        $model = array();
        if (isset($_GET['service']) && is_numeric($_GET['service']) && $_GET['service'] >= 0) {
            $model = Service::model()->findByPk($_GET['service']);
        }
        $this->render(
                'request/index', array(
            'service' => $model,
            'customer' => $customer,
            'merchant' => $merchant
        ));
    }

    /**
     * Booking for TRIAL Merchant
     */
    public function actionTrialBooking() {
        if (!isset($_GET['service'])) {
            throw new CHttpException(404, 'Not found trial booking line: 1575');
        }

        if (Yii::app()->user->isGuest) {
            $customer = new Users();
            if (isset($_POST['ajax']) && $_POST['ajax'] === 'book-form') {
                echo CActiveForm::validate($customer);
                Yii::app()->end();
            }
        } else {
            $customer = Users::model()->findByPk(Yii::app()->user->id);
        }
        $model = Service::model()->findByPk($_GET['service']);

        $this->render('trial/index', array(
            'service' => $model,
            'customer' => $customer
        ));
    }

    /**
     * Use at frontend/booking/index?service=3
     * @return list free time of staff
     */
    public function actionGetFulltimeForTrialMerchant() {
        $morning = Utils::minuteStep(5, '06:00', '12:00', FALSE);
        $afternoon = Utils::minuteStep(5, '13:00', '18:00', FALSE);
        $evening = Utils::minuteStep(5, '19:00', '22:00', FALSE);

        $result_arr = array(
            'morning' => $morning, 'afternoon' => $afternoon, 'evening' => $evening);

        echo json_encode($result_arr);
        Yii::app()->end();
    }

    public function actionCreateTrialAppt() {
//service id
        $s_id = $_POST['sid'];
        $service = Service::getRecordbySid($s_id);
        //customer id
        $cus_id = null;
//create Customer
        if (Yii::app()->user->isGuest) {
//check customer by email
            $cus = Users::check_exist_by_email($_POST['email'], Users::TYPE_CUSTOMER);

            //if user exited in tbl_user
            if ($cus != NULL) {
//kiem tra xem user co thuoc biz khong
                $check_cus_biz = Customer::checkCustomerBelongToBiz($cus->id, $service->biz->id);

//neu customer la khach hang cua biz
//lay id cua customer
                if ($check_cus_biz) {
                    $cus_id = $check_cus_biz->id;
                } else {
                    $new_cus = $this->createCustomerBiz($cus->id, $service->biz->id);
                    $cus_id = $new_cus->id;
                }
            } else { //if email not exited in tbl_user
//create new user in
                $user = $this->createNewUser();
//create new customer in tbl_customer
                $new_cus = $this->createCustomerBiz($user->id, $service->biz->id);
                $cus_id = $new_cus->id;
            }
        }
//update Customer
        else {
            $customer = Users::model()->findByPk(Yii::app()->user->getId());
            $customer->firstname = $_POST['fname'];
            $customer->lastname = $_POST['lname'];
//            $customer->email = $_POST['email'];
            $customer->mobile_phone = $_POST['phone'];
            $customer->occupation = $_POST['occupation'];
            $birthday = ($_POST['birthday'] != '') ? str_replace('/', '-', $_POST['birthday']) : NULL;
            $customer->birthday = strtotime($birthday);
            $customer->save();

//kiem tra customer hien tai  co thuoc biz khong?
            $check_cus_biz = Customer::checkCustomerBelongToBiz($customer->id, $service->biz->id);

            if ($check_cus_biz != NULL) {
                $cus_id = $check_cus_biz->id;
            } else {
                $new_cus = $this->createCustomerBiz(Yii::app()->user->getId(), $service->biz->id);
                $cus_id = $new_cus->id;
            }
        }

// Tạo Appointment
        $time = $_POST['time'];

        $appointment = new TrialAppoint();
        $appointment->biz_id = $service->user->author_id;
        $appointment->s_id = $s_id;
        $appointment->cus_id = $cus_id;
        $appointment->note = $_POST['note'];
        $appointment->date = strtotime(str_replace('/', '-', $_POST['date']));
        $appointment->start_time = ltrim($time, '0');
        $appointment->end_time = Utils::plusminute($time, $service->duration, $service->recover);
        $appointment->status = Appoint::BOOKING_STATUS_PENDING;
        if ($appointment->save() && $appointment->validate()) {
//send mail order confirm
            EmailConfirm::send($customer->email, $customer->name, $appointment, $check_cus_biz, TRUE);
            echo json_encode(array(
                'status' => 'ok',
                'cus_email' => $customer->email,
                'cus_name' => $customer->name,
                'cus_key' => $check_cus_biz->ckey,
                'apt_id' => $appointment->id,
            ));
            Yii::app()->end();
        } else {
            echo json_encode(array(
                'status' => 'err'
            ));
            Yii ::app()->end();
        }
    }

    public function actionConfirmTrialBooking() {
        if (empty($_GET)) {
            Yii::app()->user->setFlash('error', Yii::t('frontend','Something wrong or time expired!'));
        }
        $appoint = TrialAppoint::model()->findByPk($_GET['appoint']);
        $customer = Customer::getRecordByCkey($_GET['ckey']);
        $service = $appoint->service;

        $confirm = EmailConfirm::model()->find('email=:e AND code=:c AND expire > :t AND type=:type', array(
            ':e' => $customer->email,
            ':c' => $_GET['code'],
            ':t' => time(),
            ':type' => EmailConfirm::TYPE_BOOKING
        ));

        if (!$appoint or ! $customer or ! $confirm) {
            Yii::app()->user->setFlash('error', Yii::t('frontend','Something\'s gone wrong!'));
        } else {
            Yii::app()->user->setFlash('success', Yii::t('frontend','Your reservation has been confirmed.'));
            if ($appoint->status != Appoint::BOOKING_STATUS_CONFIRM) {
                $appoint->status = Appoint::BOOKING_STATUS_CONFIRM;
                if ($appoint->save() AND $confirm->save()) {
                    $isc_file = Helper::createICSFile($appoint, $customer);
                    MyEmail ::NewAppointToCus($appoint, $customer, $isc_file);
                    MyEmail::NewAppointToBiz($appoint, $customer, $isc_file);
                }
            }
        }

        $this->render('confirm', array
            (
            'service' => $service,
            'customer' => $customer
        ));
    }

    /**
     * Reviews Function
     */
    public function actionAjaxLoadReview() {
        $sid = $_POST['sid'];
        if (isset(Yii::app()->session['offset_review'])) {
            $offset = Yii::app()->session['offset_review'] + 8;
            Yii::app()->session['offset_review'] = $offset;
        } else {
//first load from 4
            $offset = Yii::app()->session['offset_review'] = 5;
        }
        $cri = new CDbCriteria();
        $cri->select = array('avatar', 'cus_id', 'firstname', 'lastname', 'average', 'date', 'comment');
        $cri->compare('sid', $sid);
        $cri->compare('status', Review::STATUS_ACTIVE);
        $cri->offset = $offset;
        $cri->order = 'date DESC';
        $cri->limit = 8;
        $model = Review::model()->findAll($cri);
//check next turn has record
        $total = Review::model()->count("sid=$sid");
        $next = $offset + 8 >= $total ? FALSE : TRUE;
        $result = array();
        $data = array();
        foreach ($model as $v) {
            $data[] = array(
                'publicAvatar' => $v->publicAvatar,
                'customerName' => $v->customerName,
                'countUserReview' => $v->countUserReview,
                'average' => $v->average,
                'date' =>
                Utils::getTextTime($v->date),
                'comment' => $v->comment,
            );
        }
        $result['next'] = $next;
        $result['data'] = $data;
        echo json_encode($result);
    }

}

class Paypal {

    var $currency = 'SGD';
    var $data = array();
    var $status = '';
    var $payment = array();
    var $redirectUrl = '';
    var $success = '';
    var $PayerID = '';
    var $result = array();

    public function actionPay() {
        require(Yii::app()->basePath . '/extensions/paypal/sample/bootstrap.php');
        $card_type = $_POST['card_type'];
        $card_number = $_POST['card_number']; //'6011773066170610';//
        $card_expire_month = $_POST['card_expire_month']; //'3';//
        $card_expire_year = $_POST['card_expire_year']; //'2019';//
        $card_csc = $_POST['card_csc']; //'012';//

        $card = new PayPal\Api\CreditCard();
        $card->setType($card_type)
                ->setNumber($card_number)->setExpireMonth($card_expire_month)
                ->setExpireYear($card_expire_year)
                ->setCvv2($card_csc);

        $fi = new PayPal\Api\FundingInstrument();
        $fi->setCreditCard($card);

        $payer = new PayPal\Api\Payer();
        $payer->setPaymentMethod("credit_card")
                ->setFundingInstruments(array($fi));

        $price = $this->data ['price'];
//$tax = $this->data['tax_total'];
//$tax = round($tax * $price / 100, 2);
        $discount = $this->data['discount'];
        $subtotal = round($price - ($price * $discount ) / 100, 2);
        $total = $subtotal; // + $tax;
//$tax = $this->formatMoney($tax, true);
        $subtotal = $this->formatMoney($subtotal, true);
        $total = $this->formatMoney($total, true);

        $item1 = new PayPal\Api\Item();
        $item1->setName($this->data['s_name'])
                ->setCurrency($this->currency)
                ->setQuantity(1)
                ->setPrice($subtotal);

        $itemList = new PayPal\Api\ItemList();
        $itemList->setItems(array($item1));

        $details = new PayPal\Api\Details();
        $details->setTax(0)
                ->setSubtotal($subtotal);

        $amount = new PayPal\Api\Amount();
        $amount->setCurrency($this->currency)
                ->setTotal($total)
                ->setDetails($details);

        $transaction = new PayPal\Api\Transaction();
        $transaction->setAmount($amount)
                ->setItemList($itemList)
                ->setDescription("Hotdeal Payment");

        $payment = new PayPal\Api\Payment();
        $payment->setIntent("sale")
                ->setPayer($payer)
                ->setTransactions(array($transaction));

        try {
            $payment->create($apiContext);
        } catch (PayPal\Exception\PPConnectionException $ex) {
            $err = json_decode($ex->getData());
            //var_dump($err); exit;
            $this->status = $err->message;
        }

        if ($this->status == ''
        ) {
            $this->status = 'ok';
            $this->payment = $payment;
        }
//var_dump($this->status);
//pay_key
//transactionID
//datetime
    }

    public function actionRedirectPaypal() {
        require(Yii::app()->basePath . '/extensions/paypal/sample/bootstrap.php');
        $payer = new PayPal\Api\Payer();
        $payer->setPaymentMethod("paypal");

        $price = $this->data['price'];
        $tax = $this->data['tax_total'];
        $tax = 0; //round($tax * $price / 100, 2);
        $discount = $this->data['discount'];
        $subtotal = round($price - ($price * $discount) / 100, 2);
        $total = $subtotal; //+ $tax;

        $tax = $this->formatMoney($tax, true);
        $subtotal = $this->formatMoney($subtotal, true);
        $total = $this->formatMoney($total, true);

        $item1 = new PayPal\Api\Item();
        $item1->setName($this->data['s_name'])
                ->setCurrency($this->currency)
                ->setQuantity(1)
                ->setPrice($subtotal);

        $itemList = new PayPal\Api\ItemList();
        $itemList->setItems(array($item1));

        $details = new PayPal\Api\Details();
        $details->setTax($tax)
                ->setSubtotal($subtotal);

        $amount = new PayPal\Api\Amount();
        $amount->setCurrency($this->currency)
                ->setTotal($total)
                ->setDetails($details);

        $transaction = new PayPal\Api\Transaction();
        $transaction->setAmount($amount)
                ->setItemList($itemList)
                ->setDescription("Hotdeal Payment");

        $baseUrl = getBaseUrl();
        $redirectUrls = new PayPal\Api\RedirectUrls();

//        date:13/May/2014
//staff_time:6131_14:40
//fname:Nguyễn
//lname:Đức
//email:anhduc.bkhn@gmail.com
//phone:0984 634 542
//occupation:Siêu nhân
//address:477 Minh Khai 
//postal_code:12345
//birthday:15/May/2014
//note:First book 
        //sid:14
        //card_number:
        //card_expire_month:
        //card_expire_year:
        //card_csc:
        //pay_type:2
        $redirectUrls->setReturnUrl(Yii::app()->createAbsoluteUrl('frontend/booking/execute', array(
                            'success' => 'true',
                            'sid' => $_POST['sid'], //service id
                            'firstname' => $_POST['fname'],
                            'lastname' => $_POST['lname'],
                            'email' => $_POST['email'],
                            'phone' => $_POST['phone'],
                            'occupation' => $_POST['occupation'],
                            'birthday' => $_POST['birthday'], //11/Jun/1992
                            'staff_time' => $_POST['staff_time'], // 4324_10:20
                            'note' => $_POST['note'],
                            'date' => $_POST['date'],
                            'address' => $_POST['address'],
                            'postal_code' => $_POST['postal_code']
                ))) //actionExecute
                ->setCancelUrl(Yii::app()->createAbsoluteUrl('frontend/booking/execute', array('success' => 'false')));

        $payment = new PayPal\Api\Payment();
        $payment->setIntent("sale")
                ->setPayer($payer)
                ->setRedirectUrls($redirectUrls)
                ->setTransactions(array($transaction));

        try {
            $payment->create($apiContext);
        } catch (PayPal\Exception\PPConnectionException $ex) {
            $err = json_decode($ex->getData());
            $this->status = $err->details[0]->issue;
        }
        if ($this->status == '') {

            foreach ($payment->getLinks() as $link) {
                if ($link->getRel() == 'approval_url') {
                    $redirectUrl = $link->getHref();
                    break;
                }
            }

            $_SESSION['paymentId'] = $payment->getId();
            if (isset($redirectUrl)) {
                $this->redirectUrl = $redirectUrl;
                $this->status = 'Redirecting to Paypal...';
            }
        }
// ### Get redirect url
// The API response provides the url that you must redirect
// the buyer to. Retrieve the url from the $payment->getLinks()
// method
    }

    public function actionExecutePayment() {
        require(Yii::app()->basePath . '/extensions/paypal/sample/bootstrap.php');


        if ($this->success == true && $this->PayerID != '') {
// Get the payment Object by passing paymentId
// payment id was previously stored in session in
// CreatePaymentUsingPayPal.php
            $paymentId = $_SESSION['paymentId'];
            $payment = PayPal\Api\Payment::get($paymentId, $apiContext);

// PaymentExecution object includes information necessary 
// to execute a PayPal account payment. 
// The payer_id is added to the request query parameters
// when the user is redirected from paypal back to your site
            $execution = new PayPal\Api\PaymentExecution ();
            $execution->setPayerId($this->PayerID);

//Execute the payment
// (See bootstrap.php for more on `ApiContext`)

            $result = $payment->execute($execution, $apiContext);

            $this->result = $result; //tra ve doi tuong payment
        } else {
            echo "User cancelled payment.";
        }
    }

    function formatMoney($number, $fractional = false) {
        if ($fractional) {
            $number = sprintf('%.2f', $number);
        }
        while (true) {
            $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);

            if ($replaced != $number) {
                $number = $replaced;
            } else {
                break;
            }
        }
        return $number;
    }

}

/**
 * End file BookController
 */
